import { HttpError, toSuccess, useTransaction } from "@sker/core"
import { useData } from "@sker/runtime"
import { AutoTaskScript, AutoTaskScriptNotFound } from "@sker/entities"
import { z } from "zod"


export default async () => {
    const input = z.object({
        id: z.string(),
        type: z.string(),
        title: z.string(),
        name: z.string(),
        display_order: z.number(),
        timeout: z.number(),
        code: z.string()
    })
    const body = input.parse(useData())
    const id = parseInt(body.id)
    await useTransaction(async m => {
        if (body.type === `2`) {
            const notfound = await m.findOne(AutoTaskScriptNotFound, { where: { id: id } })
            if (!notfound) throw new HttpError(`没有找到AutoTaskScriptNotFound`)
            const item = await m.findOne(AutoTaskScript, {
                where: {
                    task_name: notfound.task_name,
                    package_name: notfound.package_name
                }
            })
            const data = m.create(AutoTaskScript, {
                id: item?.id,
                title: body.title,
                name: body.name,
                display_order: body.display_order,
                timeout: body.timeout,
                code: body.code,
                task_name: notfound.task_name,
                package_name: notfound.package_name
            })
            await m.save(data)
        } else {
            const data = m.create(AutoTaskScript, {
                id: id,
                title: body.title,
                name: body.name,
                display_order: body.display_order,
                timeout: body.timeout,
                code: body.code,
            })
            await m.save(data)
        }
    })
    return toSuccess(body)
}